const express = require('express');
const router = express.Router();
const mysql = require('mysql2');
const { db } = require('../config');
const pool = mysql.createPool(db);

// 添加商品到购物车
router.post('/', (req, res) => {
  const { user_id, goods_id, quantity } = req.body;
  if (!user_id || !goods_id || !quantity) {
    return res.status(400).json({ code: 1, message: '参数不完整' });
  }
  // 如果已存在则数量累加，否则插入新记录
  pool.query(
    'SELECT * FROM cart WHERE user_id = ? AND goods_id = ?',
    [user_id, goods_id],
    (err, results) => {
      if (err) return res.status(500).json({ code: 1, message: '数据库错误' });
      if (results.length > 0) {
        // 已存在，更新数量
        pool.query(
          'UPDATE cart SET quantity = quantity + ? WHERE user_id = ? AND goods_id = ?',
          [quantity, user_id, goods_id],
          (err2) => {
            if (err2) return res.status(500).json({ code: 1, message: '数据库错误' });
            res.json({ code: 0, message: '加入购物车成功' });
          }
        );
      } else {
        // 不存在，插入新记录
        pool.query(
          'INSERT INTO cart (user_id, goods_id, quantity) VALUES (?, ?, ?)',
          [user_id, goods_id, quantity],
          (err3) => {
            if (err3) return res.status(500).json({ code: 1, message: '数据库错误' });
            res.json({ code: 0, message: '加入购物车成功' });
          }
        );
      }
    }
  );
});

// 获取购物车列表（带商品信息）
router.get('/', (req, res) => {
  const user_id = req.query.user_id;
  if (!user_id) {
    return res.status(400).json({ code: 1, message: '缺少用户ID' });
  }
  pool.query(
    'SELECT cart.id, cart.quantity, goods.name, goods.price, goods.image FROM cart JOIN goods ON cart.goods_id = goods.id WHERE cart.user_id = ?',
    [user_id],
    (err, results) => {
      if (err) return res.status(500).json({ code: 1, message: '数据库错误' });
      res.json({ code: 0, data: results });
    }
  );
});

// 删除购物车商品
router.delete('/:id', (req, res) => {
  const id = req.params.id;
  pool.query('DELETE FROM cart WHERE id = ?', [id], (err) => {
    if (err) return res.status(500).json({ code: 1, message: '数据库错误' });
    res.json({ code: 0, message: '删除成功' });
  });
});

module.exports = router; 